package demo

import (
	"encoding/json"
	"fmt"
	"net"
	"strings"
)

func Subscription(myMap map[string]string) string {
	fmt.Println(myMap)
	return "订阅成功"
}

func udp_socket() {
	addr := net.UDPAddr{
		Port: 30000,
		IP:   net.ParseIP("127.0.0.1"),
	}
	conn, err := net.ListenUDP("udp", &addr)
	if err != nil {
		fmt.Printf("Some error %v", err)
		return
	}
	for {
		message := make([]byte, 4096)
		n, remaddr, err := conn.ReadFromUDP(message)
		if err != nil {
			fmt.Printf("Some error  %v", err)
			continue
		}
		fmt.Printf("来自: %v\n内容: %s\n", remaddr, string(message[:n]))
		str := string(message[:n])
		str = strings.Replace(str, "'", "\"", -1)
		myMap := make(map[string]string)
		errs := json.Unmarshal([]byte(str), &myMap)
		if errs != nil {
			fmt.Println(errs)
		}

		x := Subscription(myMap)
		// 发送
		_, err = conn.WriteToUDP([]byte(x), remaddr)
		if err != nil {
			fmt.Println("Error writing to UDP:", err)
		}
	}
}
